<template lang="pug">
  h4 Graphic
  ul.grallery
    li(v-for="(graphic, idx) in graphics") 
      div.dialog-svg-wrapper(v-html="graphic.svgCode" )
      span.note {{ `${graphic.name}`  }}
  div(v-show="isSvgCode")
    div.dialog-svg-wrapper(v-html="formData.svgCode" )
  form(@submit.prevent="handleSubmit")
    input(type="text" v-model="formData.name" placeholder="name")
    label(for="checkbox") colorful
      input(type="checkbox" id="checkbox" v-model="formData.isColorful" )
    textarea.svg-code-textarea(v-model="formData.svgCode" placeholder="svg code" )
    br
    button(type="submit" :disabled="!isSvgCode") create graphic
    button(@click="handleReset") Reset
</template>

<script setup>
import { computed, ref, watch, onMounted, inject } from 'vue';
import api from '../apis/api'
const graphics = inject('graphics')
const mainBrandId = inject('mainBrandId')

const formData = ref({
  name: '',
  brandId: mainBrandId,
  isColorful: false,
  svgCode: '',
})

const svgRegex = /<svg[\s\S]*<\/svg>/i;
const isSvgCode = computed(() => svgRegex.test(formData.value.svgCode));

const initialFormData = { ...formData.value };
const handleSubmit = async () => {
  if (!isSvgCode.value) return
  if (!formData.value.isColorful) {
    formData.value.svgCode = clearSvgCode(formData.value.svgCode)
  }
  await api.post('graphics', { ...formData.value })
  resetFormData()
};

const resetFormData = () => {
  for (let key in initialFormData) {
    formData.value[key] = initialFormData[key];
  }
};

function clearSvgCode(code) {
  return code.replace(/ style=".*?"/g, '') // 清理style属性
    .replace(/ p-id=".*?"/g, '')                    // 清理p-id属性
    .replace(/<style>[\s\S]*?<\/style>/g, '')       // 清理样式代码
    .replace(/fill=".*?"/g, '')                     // 清理填充属性
}

</script>

<style>
.grallery {
  display: flex;
  list-style: none;
}

.svg-code-textarea {
  width: 70vw;
  height: 8rem;
  padding: 0.5rem;
  overflow: hidden;
  resize: none;
}

.dialog-svg-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 4rem;
  width: 5rem;
  cursor: pointer;
}

.dialog-svg-wrapper svg {
  max-width: 3rem;
  max-height: 4rem;
}

.note {
  font-size: 0.5rem;
}
</style>
